package com.quanyan.club.task.tracker;

import com.alibaba.fastjson.JSON;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.TbClubActivity;
import com.quanyan.club.entity.db.TbOrder;
import com.quanyan.club.entity.db.TbOrderExample;
import com.quanyan.club.entity.db.TbSignUser;
import com.quanyan.club.entity.db.TbSignUserExample;
import com.quanyan.club.mapper.TbClubActivityMapper;
import com.quanyan.club.mapper.TbOrderMapper;
import com.quanyan.club.mapper.TbSignUserMapper;
import com.quanyan.club.service.ClubActivityService;
import com.quanyan.common.constants.Constants;

import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by zhuo.shi on 2016/7/9. 定时执行任务，任务开始时间 为活动报名截止时间 任务：检查此俱乐部活动是否可以开启，如果不能开启，取消活动，退款给已报名用户
 */
@Component
public class ActivityStartAbleCheckJob implements JobRunner {

    private static Logger logger = Logger.getLogger(ActivityStartAbleCheckJob.class);

    @Autowired
    private ActivityOpenService activityOpenService;
    @Autowired
    private TbClubActivityMapper clubActivityMapper;
    @Autowired
    private TbSignUserMapper signUserMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private ClubActivityService clubActivityService;

    @Override
    public Result run(JobContext jobContext) throws Throwable {

        /*Job job = jobContext.getJob();
        if (job == null) {
            return new Result(Action.EXECUTE_EXCEPTION, "任务不存在");
        }
        Map<String, String> params = job.getExtParams();
        logger.warn("俱乐部活动报名截止时间到，检查此活动是否报名人数已满任务执行，参数：" + params);

        //1. 获取活动信息，俱乐部信息
        int activityId = MapUtils.getIntValue(params, "activityId");
        int clubActivityId = MapUtils.getIntValue(params, "clubActivityId");

        //2. 判断此俱乐部是否已经被取消，暂停
        ActivityInfo activityInfo = activityOpenService.selectOneActivityById(activityId);
        logger.warn("------------活动信息：-------------" + JSON.toJSONString(activityInfo));
        Calendar calendar = Calendar.getInstance();

        calendar.add(Calendar.MINUTE, -1);
        if (activityInfo != null &&
                activityInfo.getStartTime().compareTo(calendar.getTime()) == -1){
            logger.warn("活动已经开始了, 不能取消活动！");
            return new Result(Action.EXECUTE_SUCCESS);
        }
        if (activityInfo != null &&
                !activityInfo.getStatus().equals(Constants.BYTE_ZERO)) {
            //活动状态 0 正常 1 暂停 2 取消
            logger.warn("活动被取消或暂停：" + activityInfo.getStatus());
            return new Result(Action.EXECUTE_SUCCESS);
        }
        //3. 获取俱乐部活动
        TbClubActivity clubActivity = clubActivityMapper.selectByPrimaryKey(clubActivityId);
        if (clubActivity == null){
            logger.warn("没有这个活动！");
            return new Result((Action.EXECUTE_SUCCESS));
        }
        //4. 获取活动已报名人数
        TbSignUserExample signUserExample = new TbSignUserExample();
        signUserExample.createCriteria()
                .andActivityIdEqualTo(activityId)
                .andIsCancelEqualTo(Constants.ZERO)
                .andStatusEqualTo(1);//有效
        int signCount = signUserMapper.countByExample(signUserExample);
        int minSignUp = clubActivity.getSignUpMin();
        logger.warn("signCount=" + signCount + ", minSignUp=" + minSignUp);
        //4.1 达到报名人数，结束返回
        if (signCount >= minSignUp) {
            return new Result(Action.EXECUTE_SUCCESS);
        }
        logger.warn("俱乐部活动" + activityId + "活动报名截止时间到，报名人数未满");
        //4.2 报名人数不足，退还此活动下所有报名人的实际付款，鸟蛋，抵扣金额
        clubActivityService.cancelActivity(activityId, activityInfo.getUid(), false);
*//*
        ActivityInfo activity = new ActivityInfo();
        activity.setId(activityId);
        activity.setStatus((byte) 2);//活动取消
        List<TbSignUser> signUsers = signUserMapper.selectByExample(signUserExample);
        if (signUsers.isEmpty()) {
            logger.warn("无人报名");
            activityOpenService.updateActivity(activity); //取消活动
            clubActivity.setActivityStatus((byte)3);
            clubActivityMapper.updateByPrimaryKeySelective(clubActivity);
            return new Result(Action.EXECUTE_SUCCESS);
        }
        boolean allSignUserRefud = true;
        logger.warn("活动，别进去");
        for (TbSignUser signUser : signUsers) {
            Integer orderUid = signUser.getOrderUserId();
            if (orderUid == null || signUser.getOrderId() == null) { // 代报名的，补报名的
                continue;
            }
            //查询此报名用户的订单
            TbOrderExample orderExample = new TbOrderExample();
            orderExample.createCriteria()
                    .andOrderUidEqualTo(orderUid)
                    .andActivityIdEqualTo(activityId)
                    .andOrderStatusEqualTo((byte)2);  //只有付款成功的才退款
            List<TbOrder> orders = orderMapper.selectByExample(orderExample);
            if (orders == null || orders.isEmpty()) {
                continue;
            }
            TbOrder order = orders.get(0);
            //发起退款
            logger.warn("活动到达报名截止时间，报名人数未满，活动自动取消，发起退款，退款给" + orderUid + ", 订单号：" + order.getOrderNo());
            APIResponse response = clubActivityService.cancelOrderNotify(orderUid, order.getOrderNo(), 4, "活动报名截止时间到，报名人数未满");
            if (response == null || !response.isRet()){
                allSignUserRefud = false;
            }
            logger.warn("退款返回：" +  JSON.toJSON(response));
        }
        logger.warn("活动倒数第二");
        //4.3 所有的人的钱都退回了，才取消活动。
        if (allSignUserRefud) {
            activityOpenService.updateActivity(activity);
        }
        else {
            //重试几次，如果退款成功了 TbSignUser的status会置为无效，不会重复退款。
            return new Result(Action.EXECUTE_LATER);
        }
        logger.warn("活动最后");*/
        return new Result(Action.EXECUTE_SUCCESS);
    }

}
